package com.chungkui.check.handler.impl;

import com.chungkui.check.configparser.bean.CheckConfig;
import com.chungkui.check.core.Constants;
import com.chungkui.check.core.ReSumitWallCacheService;
import com.chungkui.check.core.bean.CheckResult;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.chungkui.check.handler.CheckHandler;

import java.util.Map;

/**
 * @Author: jason
 * @Date: 2019/12/30 16:51
 * @Version 1.0
 */

public class ReSubmitWallCheckHandler implements CheckHandler {
    @Autowired(required = false)
    ReSumitWallCacheService reSumitWallCacheService;
    private static String resubmitwall = "reSubmitWall";

    @Override
    public CheckResult check(CheckConfig checkConfig, Map<String, Object> params) {
        CheckResult checkResult = new CheckResult(true);
        CheckConfig.ResumitWallConfig resumitWallConfig = checkConfig.getResumitWallConfig();
        if (resumitWallConfig != null) {

            String key = MapUtils.getString(params, resubmitwall);
            Map<String, Object> msgConfig = resumitWallConfig.getMsgConfig();
            if (!StringUtils.equals(resumitWallConfig.getPrefix(), Constants.OFF)) {
                if (StringUtils.isBlank(key)) {
                    checkResult.setIfPass(false);
                    checkResult.setCode(resumitWallConfig.getCode());
                    checkResult.setMsg(MapUtils.getString(msgConfig, Constants.NULL));
                    return checkResult;
                }
                boolean v = reSumitWallCacheService.set(resumitWallConfig.getPrefix() + ":" + key, "lock", resumitWallConfig.getExpire());
                if (!v) {
                    checkResult.setIfPass(false);
                    checkResult.setCode(resumitWallConfig.getCode());
                    checkResult.setMsg(MapUtils.getString(msgConfig, Constants.FAIL));
                    return checkResult;
                }
            }
        }

        return checkResult;
    }

    @Override
    public int sort() {
        return 2;
    }
}
